//
//  PostureViewController.m
//  FreeReading
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "PostureViewController.h"
#import "PostureCell_01.h"
#import "PotureCell_02.h"
#import "PostureCell_03.h"
#import "PostureCell_04.h"
#import "EnjoyDetailViewController.h"

@interface PostureViewController ()
{
    BOOL _isHeaderRefreshing;
    NSString *_nextUrl;
}

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation PostureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PostureCell_01" bundle:nil] forCellReuseIdentifier:@"postureCell1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"PotureCell_02" bundle:nil] forCellReuseIdentifier:@"potureCell2"];
    [self.tableView registerNib:[UINib nibWithNibName:@"PostureCell_03" bundle:nil] forCellReuseIdentifier:@"postureCell3"];
    [self.tableView registerNib:[UINib nibWithNibName:@"PostureCell_04" bundle:nil] forCellReuseIdentifier:@"postureCell4"];
    
    self.dataArray = [NSMutableArray array];
    [self setUpRefresh];
    
    
}



- (void)data
{
    if (_isHeaderRefreshing) {
        _nextUrl = kPosture;
    } else {
        
        if ([_nextUrl isEqualToString:@""]) {
            
            [self.tableView.footer noticeNoMoreData];
        }
    }
   
    
    // 判断网络状态
    AFNetworkReachabilityManager *net_manager = [AFNetworkReachabilityManager sharedManager];
    [net_manager startMonitoring];
    [net_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络异常 请检查网络后重试" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
                [self.tableView.header endRefreshing];
                
                return ;
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
        
        
    }];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:_nextUrl parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        NSDictionary *dic = responseObject[@"data"];
        
        NSDictionary *dictt = dic[@"info"];
        
        _nextUrl =[NSString stringWithFormat:@"%@%@", dictt[@"next_url"], @"&_bsize=720_1280&_version=6.41"];
        
        
        NSArray *arr = dic[@"articles"];
        
        NSMutableArray *temoArray = [NSMutableArray array];
        for (NSDictionary *dict in arr) {
            
            PostureModel *model = [[PostureModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dict];
            
            
            [temoArray addObject:model];
            
            
            
        }
        
        if (_isHeaderRefreshing) {
            
            self.dataArray = temoArray;
            [self.tableView.header endRefreshing];
            [self.tableView reloadData];
        }  else {
            
            [self.dataArray addObjectsFromArray:temoArray];
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        
       
        
        [self.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
        
    }];
    
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        
        self.view = nil;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    return self.dataArray.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PostureModel *model = self.dataArray[indexPath.row];
    
    if (!self.dataArray.count > 0) {
        
        return nil;
    } else {
    
        if ([model.special_info[@"item_type"] isEqualToString:@"1_b"]) {
            
            PostureCell_01 *cell1 = [tableView dequeueReusableCellWithIdentifier:@"postureCell1" forIndexPath:indexPath];
            
            cell1.titleLabel.font = [UIFont systemFontOfSize:14];
            cell1.placeLabel.font = [UIFont systemFontOfSize:12];
            cell1.timeLabel.font = [UIFont systemFontOfSize:12];
            
            cell1.titleLabel.text = model.title;
            cell1.placeLabel.text = model.auther_name;
            cell1.timeLabel.text = [self getTimeStringWithTime:model.date];
            [cell1.picture sd_setImageWithURL:[NSURL URLWithString:model.thumbnail_medias.firstObject[@"url"]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            
            
            return cell1;
            
        } else if ([model.special_info[@"item_type"] isEqualToString:@"3_b"]) {
            
            PotureCell_02 *cell2 = [tableView dequeueReusableCellWithIdentifier:@"potureCell2" forIndexPath:indexPath];
            
            
            cell2.titleLabel.font = [UIFont systemFontOfSize:14];
            cell2.palceLabel.font = [UIFont systemFontOfSize:12];
            cell2.timeLabel.font = [UIFont systemFontOfSize:12];
            
            cell2.titleLabel.text = model.title;
            cell2.palceLabel.text = model.auther_name;
            cell2.timeLabel.text = [self getTimeStringWithTime:model.date];
            
            NSString *url = model.thumbnail_medias[0][@"url"];
            [cell2.picture01 sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            NSString *url1 = model.thumbnail_medias[1][@"url"];
            [cell2.picture02 sd_setImageWithURL:[NSURL URLWithString:url1] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            NSString *url2 = model.thumbnail_medias[2][@"url"];
            [cell2.picture03 sd_setImageWithURL:[NSURL URLWithString:url2] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            
            
            
            
            return cell2;
            
        } else if ([model.special_info[@"item_type"] isEqualToString:@"1"]) {
            PostureCell_03 *cell3 = [tableView dequeueReusableCellWithIdentifier:@"postureCell3" forIndexPath:indexPath];
            
            cell3.titleLabel.font = [UIFont systemFontOfSize:14];
            cell3.titleLabel.numberOfLines = 0;
            cell3.placeLabel.font = [UIFont systemFontOfSize:12];
            cell3.timeLabel.font = [UIFont systemFontOfSize:12];
            
            cell3.titleLabel.text = model.title;
            cell3.titleLabel.numberOfLines = 0;
            
            
            
            cell3.timeLabel.text = [self getTimeStringWithTime:model.date];
            
            
            
            cell3.placeLabel.text = model.auther_name;
            
            [cell3.piture sd_setImageWithURL:[NSURL URLWithString:model.thumbnail_medias.firstObject[@"url"]] placeholderImage:[UIImage imageNamed:@"placeholder"]];
            
            
            return cell3;
            
        } else {
            
            PostureCell_04 *cell4 = [tableView dequeueReusableCellWithIdentifier:@"postureCell4" forIndexPath:indexPath];
            
            
            cell4.timeLabel.font = [UIFont systemFontOfSize:14];
            cell4.placeLabel.font = [UIFont systemFontOfSize:12];
            cell4.timeLabel.font = [UIFont systemFontOfSize:12];
            
            cell4.titleLabel.text = model.title;
            cell4.placeLabel.text = model.auther_name;
            cell4.timeLabel.text = [self getTimeStringWithTime:model.date];
            
            return cell4;
            
        }

    
    
    
    }
    
    

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    PostureModel *model = self.dataArray[indexPath.row];
    if ([model.special_info[@"item_type"] isEqualToString:@"1_b"]) {
        
        return 283;
    } else if ([model.special_info[@"item_type"] isEqualToString:@"3_b"]) {
        
    
        return 204;
    } else if ([model.special_info[@"item_type"] isEqualToString:@"1"]) {
        
        
        return 104;
        
    } else  {
    
        
        return 104;
    }
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EnjoyDetailViewController *enjoyVC = [[EnjoyDetailViewController alloc] init];
    
    PostureModel *model = self.dataArray[indexPath.row];
    enjoyVC.url = model.weburl;
    enjoyVC.newsTitle  = model.title;
    enjoyVC.pic_url = model.thumbnail_medias[0][@"url"];
    enjoyVC.tag = @"2";
    [self.navigationController pushViewController:enjoyVC animated:YES];
    
}



- (NSString *)getTimeStringWithTime:(NSString *)string
{

NSDateFormatter *formate = [[NSDateFormatter alloc] init];
[formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *data = [formate dateFromString:string];

 return [data timeIntervalDescription];

}



#pragma mark - 刷新数据
- (void)setUpRefresh
{
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headRefresh)];
    
    [self.tableView.header beginRefreshing];
    
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footRefresh)];
}

- (void)headRefresh
{
    
    _isHeaderRefreshing = YES;
    [self data];
    
    
}


- (void)footRefresh
{
    
    _isHeaderRefreshing = NO;
    [self data];
    
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
